package com.netease.nim.demo.session.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.DynamicDrawableSpan;
import android.view.View;
import android.widget.Toast;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.netease.nim.demo.contact.cache.TeamDataCache;
import com.netease.nim.demo.contact.cache.TeamMemberInfoCache;
import com.netease.nim.demo.main.model.Extras;
import com.netease.nim.demo.session.activity.AbsBaseMessageActivity.TitleView;
import com.netease.nim.demo.session.announcement.AnnouncementView;
import com.netease.nim.demo.session.model.MsgListItem;
import com.netease.nim.demo.team.activity.TeamInfoActivity;
import com.netease.nim.demo.team.activity.TeamNicknameActivity;
import com.netease.nim.demo.util.LogUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.team.TeamService;
import com.netease.nimlib.sdk.team.model.Team;
import com.netease.nimlib.sdk.team.model.TeamMember;
import com.shwread.android.qysw.activity.NewInteractionAtlasSeeActivity;
import com.shwread.android.qysw.activity.NewInteractionCreateTeamChMActivity;
import com.shwread.android.qysw10000136.R;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.Logger;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import logic.bean.ContactInfo;
import logic.bean.TeamMemberX;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.Utils;


/**
 * 群聊界面
 * <p/>
 * Created by huangjun on 2015/3/5.
 */
public class TeamMessageActivity
        extends
        AbsMessageActivity
        implements
        AnnouncementView.AnnouncementOnClickListener,
        TitleView {

    // model
    private Team team;

    private View invalidTeamTipView;

    @Override
    protected int getResId() {
        return R.layout.message_activity;
    }

    @Override
    public SessionTypeEnum getSessionTypeEnum() {
        return SessionTypeEnum.Team;
    }

    public static void start(Context context, String contactid) {
        start(context, contactid, null);
    }

    public static void start(Context context, String contactid, Intent extras) {
        start(context, contactid, extras, true);
    }

    public static void start(Context context, String contactid, Intent extras, boolean clearTop) {
        Intent intent = new Intent();
        intent.putExtra(Extras.EXTRA_ACCOUNT, contactid);
        intent.setClass(context, TeamMessageActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (clearTop) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }
        if (extras != null) {
            intent.putExtras(extras);
        }
        ((Activity) context).startActivityForResult(intent, TeamNicknameActivity.REQ_CODE_TEAM_NAME);
    }

    @Override
    protected void onParseIntent() {
        receiverid = getIntent().getStringExtra(Extras.EXTRA_ACCOUNT);
        updateTeamInfo(TeamDataCache.getInstance().getTeamById(receiverid));
    }

    @Override
    protected void findViews() {
        super.findViews();
        invalidTeamTipView = findViewById(R.id.invalid_team_tip);
        messageEditText.setFilters(new InputFilter[]{
                new MyInputFilter()
        });
        //		messageEditText.addTextChangedListener(new TextWatcher()
        //		{
        //
        //			@Override
        //			public void onTextChanged(CharSequence s, int start, int before, int count) {
        //				String str = messageEditText.getText().toString();
        //				if (Utils.isNotEmpty(str))
        //				{
        //					String endStr = str.substring(str.length() - 1, str.length());
        //					if (endStr.equals("@"))
        //					{
        //						Intent intent = new Intent(TeamMessageActivity.this, NewInteractionCreateTeamChMActivity.class);
        //						intent.putExtra(DefaultConsts.NI_CONTACT_INTENT, DefaultConsts.NI_CONTACT_GET_MEMBER);
        //						intent.putExtra("teamId", team.getId());
        //						startActivityForResult(intent, TeamInfoActivity.GET_MEMBER_CODE);
        //						//					Toast.makeText(context, "@@@@@@@@@@", 1000).show();
        //					}
        //				}
        //			}
        //
        //			@Override
        //			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        //
        //			}
        //
        //			@Override
        //			public void afterTextChanged(Editable s) {
        //			}
        //
        //		});
    }

    @Override
    public boolean isTeam() {
        return true;
    }

    /**
     * 识别输入框的是不是@符号
     */
    private class MyInputFilter
            implements
            InputFilter {

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            // TODO Auto-generated method stub
            if (source.toString().equalsIgnoreCase("@") || source.toString().equalsIgnoreCase("＠")) {
                goAt();
            }

            return source;
        }
    }

    private void goAt() {
        StringBuffer tmp = new StringBuffer();
        // 把选中人的id已空格分隔，拼接成字符串
        for (Map.Entry<String, String> entry : cidNameMap.entrySet()) {
            tmp.append(entry.getKey() + " ");
        }
        Intent intent = new Intent(TeamMessageActivity.this, NewInteractionCreateTeamChMActivity.class);
        intent.putExtra(DefaultConsts.NI_CONTACT_INTENT, DefaultConsts.NI_CONTACT_GET_MEMBER);
        intent.putExtra("teamId", team.getId());
        intent.putExtra(NewInteractionCreateTeamChMActivity.KEY_SELECTED, tmp.toString());
        startActivityForResult(intent, TeamInfoActivity.GET_MEMBER_CODE);
    }

    /**
     * 存储@的cid、name对
     */
    private Map<String, String> cidNameMap = new HashMap<String, String>();

    /**
     * 选中的@的人的cid,进入@列表时，需要传递过去
     */
    private String selectedCids;

    /**
     * 返回的所有的用户名,用于识别输入框中的所有要@的人
     * 如果用户删除过，会出现不匹配的情况，需要在for循环中做处理
     */
    private String nameStr;

    /**
     * 上一次返回的用户名，用于把要@的用户名拼接到输入框中
     */
    private String lastNameStr;

    private void setAtImageSpan(String nameStr) {

        String content = String.valueOf(messageEditText.getText());
        if (content.endsWith("@") || content.endsWith("＠")) {
            content = content.substring(0, content.length() - 1);
        }
        String tmp = content;

        SpannableString ss = new SpannableString(tmp);

        if (nameStr != null) {
            String[] names = nameStr.split(" ");
            if (names != null && names.length > 0) {
                for (String name : names) {
                    if (name != null && name.trim().length() > 0) {
                        final Bitmap bmp = getNameBitmap(name);

                        // 这里会出现删除过的用户，需要做判断，过滤掉
                        if (tmp.indexOf(name) >= 0 && (tmp.indexOf(name) + name.length()) <= tmp.length()) {

                            // 把取到的要@的人名，用DynamicDrawableSpan代替
                            ss.setSpan(new DynamicDrawableSpan(DynamicDrawableSpan.ALIGN_BASELINE) {

                                @Override
                                public Drawable getDrawable() {
                                    // TODO Auto-generated method stub
                                    BitmapDrawable drawable = new BitmapDrawable(getResources(), bmp);
                                    drawable.setBounds(0, 0, bmp.getWidth(), bmp.getHeight());
                                    return drawable;
                                }
                            }, tmp.indexOf(name), tmp.indexOf(name) + name.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                    }
                }
            }
        }
        messageEditText.setTextKeepState(ss);
    }

    /**
     * 把返回的人名，转换成bitmap
     *
     * @param name
     * @return
     */
    private Bitmap getNameBitmap(String name) {

		/* 把@相关的字符串转换成bitmap 然后使用DynamicDrawableSpan加入输入框中 */

        name = "" + name;
        Paint paint = new Paint();
        paint.setColor(getResources().getColor(R.color.common_blue));
        paint.setAntiAlias(true);
        paint.setTextSize(32);
        Rect rect = new Rect();

        paint.getTextBounds(name, 0, name.length(), rect);

        // 获取字符串在屏幕上的长度
        int width = (int) (paint.measureText(name));

        final Bitmap bmp = Bitmap.createBitmap(width, rect.height(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);

        canvas.drawText(name, rect.left, rect.height() - rect.bottom, paint);

        return bmp;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerTeamUpdateObserver(true);
        setTitleView(this);
        if (TeamMemberInfoCache.getInstance().getTeamMember(receiverid) != null) {
            refreshMessageList();
            requestTeamInfo();
        } else {
            getTeamMemberInfoByTeamId(receiverid);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        registerTeamUpdateObserver(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
//		if (TeamMemberInfoCache.getInstance().getTeamMember(receiverid) != null)
//		{
//			refreshMessageList();
//			requestTeamInfo();
//		}
//		else
//		{
//			getTeamMemberInfoByTeamId(receiverid);
//		}
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * 请求群和群成员基本信息
     */
    private void requestTeamInfo() {
        // 请求群基本信息
        Team t = TeamDataCache.getInstance().getTeamById(receiverid);
        if (t != null) {
            updateTeamInfo(t);
        } else {
            NIMClient.getService(TeamService.class).queryTeam(receiverid).setCallback(new RequestCallback<Team>() {
                @Override
                public void onSuccess(Team team) {
                    if (team != null) {
                        TeamDataCache.getInstance().addOrUpdateTeam(team);
                        updateTeamInfo(team);
                    } else {
                        onRequestTeamInfoFailed();
                        LogUtil.e(TAG, "request team info failed, team is null");
                    }
                }

                @Override
                public void onFailed(int code) {
                    onRequestTeamInfoFailed();
                    LogUtil.e(TAG, "request team info failed, error code =" + code);
                }

                @Override
                public void onException(Throwable exception) {
                    onRequestTeamInfoFailed();
                }
            });
        }
    }

    private void getTeamMemberInfoByTeamId(final String teamId) {
        NewActionHelp.qryMemberListByTeamId(context, teamId, new ObjectHttpResponseHandler<List<TeamMemberX>>() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                String errorMsg = "request team member list failed :" + statusCode;
                LogUtil.e(TAG, errorMsg);
                requestTeamInfo();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, List<TeamMemberX> object, String responseString) {
                if (object != null && !object.isEmpty()) {
                    TeamMemberInfoCache.getInstance().addTeam(teamId, object);
                    TeamMemberInfoCache.getInstance().add(object);
                    refreshMessageList();
                }
                requestTeamInfo();
            }

            @Override
            public Type getType() {
                return new TypeToken<List<TeamMemberX>>() {
                }.getType();
            }
        });
    }

    private void onRequestTeamInfoFailed() {
        //Toast.makeText(TeamMessageActivity.this, "获取群信息失败!", Toast.LENGTH_SHORT);
        finish();
    }

    /**
     * 更新群信息
     *
     * @param d
     */
    private void updateTeamInfo(final Team d) {
        if (d == null) {
            return;
        }

        team = d;
        setTitle(team == null ? receiverid : team.getName() + "(" + team.getMemberCount() + ")");
        if (null != invalidTeamTipView) {
            invalidTeamTipView.setVisibility(team.isMyTeam() ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TeamInfoActivity.REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                String reason = data.getStringExtra(TeamInfoActivity.RESULT_EXTRA_REASON);
                boolean finish = reason != null && (reason.equals(TeamInfoActivity.RESULT_EXTRA_REASON_DISMISS) || reason.equals(TeamInfoActivity.RESULT_EXTRA_REASON_QUIT));
                if (reason != null && reason.equals(TeamInfoActivity.RESULT_EXTRA_REASON_CLEAR)) {
                    items.clear();
                    adapter.notifyDataSetChanged();
                }
                if (finish) {
                    finish(); // 退出or解散群直接退出多人会话
                }
            }
        }
        if (requestCode == TeamInfoActivity.GET_MEMBER_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                String tmpCidStr = data.getStringExtra(NewInteractionCreateTeamChMActivity.KEY_CID);
                String tmpNameStr = data.getStringExtra(NewInteractionCreateTeamChMActivity.KEY_NAME);

                String[] tmpCids = tmpCidStr.split(" ");
                String[] tmpNames = tmpNameStr.split(" ");

                if (tmpCids != null && tmpCids.length > 0) {
                    for (int i = 0; i < tmpCids.length; i++) {
                        if (tmpNames.length > i) {
                            cidNameMap.put(tmpCids[i], tmpNames[i]);
                        }
                    }
                }

                if (selectedCids == null) {
                    selectedCids = tmpCidStr;
                } else {
                    selectedCids = selectedCids + tmpCidStr;
                }

                if (nameStr == null) {
                    nameStr = tmpNameStr;

                } else {
                    nameStr = nameStr + tmpNameStr;

                }
                lastNameStr = tmpNameStr;

                // 获取光标当前位置
                int curIndex = messageEditText.getSelectionStart();

                // 把要@的人插入光标所在位置
                messageEditText.getText().insert(curIndex, lastNameStr);
                // 通过输入@符号进入好友列表并返回@的人，要删除之前输入的@
                if (curIndex >= 1) {
                    messageEditText.getText().replace(curIndex - 1, curIndex, "");
                }
                setAtImageSpan(nameStr);
            }
        }
        if (requestCode == TeamNicknameActivity.REQ_CODE_TEAM_NAME && null != data) {

            setResult(RESULT_OK, data);
        }
    }

    @Override
    public void onAnnouncementClick(String id) {
        //TODO 跳转到群公告列表页面
    }

    /**
     * 注册群信息更新监听
     *
     * @param register
     */
    private void registerTeamUpdateObserver(boolean register) {
        if (register) {
            TeamDataCache.getInstance().registerTeamDataChangedObserver(teamDataChangedObserver);
            TeamDataCache.getInstance().registerTeamMemberDataChangedObserver(teamMemberDataChangedObserver);
        } else {
            TeamDataCache.getInstance().unregisterTeamDataChangedObserver(teamDataChangedObserver);
            TeamDataCache.getInstance().unregisterTeamMemberDataChangedObserver(teamMemberDataChangedObserver);
        }
    }

    TeamDataCache.TeamDataChangedObserver teamDataChangedObserver = new TeamDataCache.TeamDataChangedObserver() {
        @Override
        public void onUpdateTeams(List<Team> teams) {
            if (team == null) {
                return;
            }
            for (Team t : teams) {
                if (t.getId().equals(team.getId())) {
                    updateTeamInfo(t);
                    break;
                }
            }
        }

        @Override
        public void onRemoveTeam(Team team) {

        }
    };

    TeamDataCache.TeamMemberDataChangedObserver teamMemberDataChangedObserver = new TeamDataCache.TeamMemberDataChangedObserver() {

        @Override
        public void onUpdateTeamMember(List<TeamMember> members) {
            refreshMessageList();
        }

        @Override
        public void onRemoveTeamMember(TeamMember member) {

        }
    };

    @Override
    protected boolean isAllowSendMessage(IMMessage message) {
        if (!team.isMyTeam()) {
            Toast.makeText(this, R.string.team_send_message_not_allow, Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    @Override
    public void onAtlasPressed(String imagelist) {
        String[] strArray = null;
        strArray = imagelist.split(",");
        final ArrayList<String> List = new ArrayList<String>();
        for (String url : strArray) {
            List.add(url);
        }
        Intent AtlasSeeIntent = new Intent();
        AtlasSeeIntent.setClass(this, NewInteractionAtlasSeeActivity.class);
        AtlasSeeIntent.putExtra(DefaultConsts.NI_ATLASSEE_URL, List);
        AtlasSeeIntent.putExtra(DefaultConsts.FROM_TYPE, DefaultConsts.NI_FROM_WEBURL);
        startActivity(AtlasSeeIntent);
    }

    private String getFromAccount;
    private Intent intentInfo = new Intent();
    private TeamMemberX teamMemberX;
    private String nickName;

    @Override
    public void onHeadImagePressed(Object item) {

        MsgListItem it = (MsgListItem) item;
        if (Utils.isEmpty(it.getMessage().getFromAccount())) {
            return;
        }
        getFromAccount = it.getMessage().getFromAccount().toString();
        teamMemberX = TeamMemberInfoCache.getInstance().getTeammMemberInfo(getFromAccount);
        if (teamMemberX != null) {
            if (Utils.isNotEmpty(teamMemberX.getStaffName())) {
                nickName = teamMemberX.getStaffName();
            } else {
                nickName = teamMemberX.getNickName();
            }
        } else {
            nickName = "";
        }
        intentInfo.putExtra(DefaultConsts.TO_P2P_PAGE_TAG, DefaultConsts.TO_P2P_PAGE_FROM_TEAM_MSG);
        intentInfo.putExtra(DefaultConsts.TO_P2P_PAGE_INFO, nickName);
        //		String str2 = getFromAccount.substring(0, 11);
        if (getFromAccount.equals(Const.UserAccId)) {
            //自己点击了自己
        } else {
            P2PMessageActivity.start(context, getFromAccount, nickName);
            //			if (Const.UserRole.equals("1"))
            //			{
            //				//登陆者为客户经理
            //				//				P2PMessageActivity.start(context, getFromAccount, intentInfo);
            //				P2PMessageActivity.start(context, getFromAccount, nickName);
            //			}
            //			else if (Const.UserRole.equals("2"))
            //			{
            //				//登陆者为客户，此时需要判断被点击者是不是该用户的客户经理，如果是跳到聊天页面，不是则不操作
            //				NewActionHelp.qryMyBoss(context, new GetMyBossInfoHandler());
            //			}
        }

    }

    class GetMyBossInfoHandler
            extends
            ObjectHttpResponseHandler<ContactInfo> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Logger.e(responseString);
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, ContactInfo object, String responseString) {
            Logger.i(responseString);
            if (object != null) {
                if (object.getAccId().equals(getFromAccount)) {
                    P2PMessageActivity.start(context, getFromAccount, nickName);
                    //					P2PMessageActivity.start(context, getFromAccount, intentInfo);
                }
            }
        }

        @Override
        public Type getType() {
            // TODO Auto-generated method stub
            return new TypeToken<ContactInfo>() {
            }.getType();
        }

    }

    @Override
    public void clickRightbutton(String receiverid) {
        TeamInfoActivity.startForTeamInfo(context, receiverid);

    }

    //长按@功能
    @Override
    public void onHeadImageLongPressed(Object item) {
        MsgListItem it = (MsgListItem) item;
        if (Utils.isEmpty(it.getMessage().getFromAccount())) {
            return;
        }
        getFromAccount = it.getMessage().getFromAccount().toString();
        teamMemberX = TeamMemberInfoCache.getInstance().getTeammMemberInfo(getFromAccount);
        if (teamMemberX != null) {
            if (Utils.isNotEmpty(teamMemberX.getStaffName())) {
                nickName = teamMemberX.getStaffName();
            } else {
                nickName = teamMemberX.getNickName();
            }
        } else {
            nickName = "";
        }
        if (getFromAccount.equals(Const.UserAccId)) {
            //点击的是自己
        } else {
            messageEditText.setText("@" + nickName + "\u3000");
        }
    }

}
